package com.allwees.core.common.util.reflect;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Java对象反射API封装
 *
 * @author yangylsky
 */
@SuppressWarnings("unchecked")
@Slf4j
public class ReflectionUtils {
	/**
	 * 反射获取Field的缓存表，为getField方法提供缓存
	 */
	private static final Map<Class<?>, Map<String, Field>> fieldCache = new HashMap<>();

	/**
	 * 反射获取Field的缓存表，为getFields方法提供缓存
	 */
	private static final Map<Class<?>, Field[]> fieldsCache = new HashMap<>();

	private ReflectionUtils() {
	}

	private static Field[] _addToFieldsCache(Class<?> clazz, Field[] fields) {
		synchronized(fieldsCache) {
			for(Field field : fields) {
				_addToFieldCache(clazz, field);
			}
			fieldsCache.put(clazz, fields);
		}
		return fields;
	}

	private static Field _addToFieldCache(Class<?> clazz, Field field) {
		Map<String, Field> subCache;
		synchronized(fieldCache) {
			subCache = fieldCache.get(clazz);
			if(subCache == null) {
				subCache = new HashMap<>();
				fieldCache.put(clazz, subCache);
			}
		}
		synchronized(subCache) {
			subCache.put(field.getName(), field);
		}
		return field;
	}

	private static Field _getCachedField(Class<?> clazz, String fieldName) {
		Map<String, Field> subCache = fieldCache.get(clazz);
		if(subCache == null) {
			return null;
		}
		return subCache.get(fieldName);
	}

	/**
	 * 直接读取对象属性值,无视private/protected修饰符,不经过getter函数.
	 */
	public static <T> T getFieldValue(final Object object, final String fieldName) {
		Field field = getField(object, fieldName);

		if(field == null) {
			// throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
			return null;
		}

		makeAccessible(field);

		T result = null;
		try {
			result = (T) field.get(object);
		} catch(IllegalAccessException e) {
			log.error("不可能抛出的异常{}" + e.getMessage());
		}
		return result;
	}

	/**
	 * 直接设置对象属性值,无视private/protected修饰符,不经过setter函数.
	 */
	public static void setFieldValue(final Object object, final String fieldName, final Object value) {
		Field field = getField(object, fieldName);

		if(field == null) {
			// throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
			if(log.isDebugEnabled()) {
				log.debug("Could not find field [{}] on target [{}]", fieldName, object);
			}
			return;
		}

		if(value != null && !field.getType().isAssignableFrom(value.getClass())) {
			//类型不兼容 - 不作处理
			return;
		}

		makeAccessible(field);

		try {
			field.set(object, value);
		} catch(IllegalAccessException e) {
			log.error("不可能抛出的异常:{}" + e.getMessage());
		}
	}

	/**
	 * 获取对象属性值, 使用getter函数.
	 */
	public static <T> T getProperty(Object o, String name) {
		try {
			return (T) PropertyUtils.getProperty(o, name);
		} catch(IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			// throw new ReflectException(e);
			return null;
		}
	}

	/**
	 * 设置对象属性值, 经过setter函数.
	 */
	public static void setProperty(Object o, String name, Object value) {
		try {
			if(PropertyUtils.isWriteable(o, name)) {
				PropertyUtils.setProperty(o, name, value);
			}
		} catch(IllegalAccessException | InvocationTargetException | NoSuchMethodException | IllegalArgumentException e) {
			// set/get方法传参类型、返回值与对应属性不一致时主动抛出异常
//			 throw new ReflectException("设置对象属性值错误", e);
		}
	}

	/**
	 * 直接调用对象方法, 无视private/protected修饰符.
	 */
	public static <T> T invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes,
			final Object[] parameters) {
		Method method = getMethod(object.getClass(), methodName, parameterTypes);
		if(method == null) {
			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
		}

		method.setAccessible(true);

		try {
			return (T) method.invoke(object, parameters);
		} catch(Exception e) {
			throw convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 循环向上转型,获取对象的DeclaredMethod. 如向上转型到Object仍无法找到, 返回null.
	 */
	public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
		for(Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
			try {
				return superClass.getDeclaredMethod(methodName, parameterTypes);
			} catch(NoSuchMethodException e) {
				// Method不在当前类定义,继续向上转型
			}
		}
		return null;
	}

	/**
	 * 判断一个对象是否有指定Property(只要有对应的read方法即可)
	 *
	 * @param object
	 * @param name
	 * @return
	 */
	public static boolean hasProperty(final Object object, final String name) {
		boolean hasProperty = false;
		try {
			PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(object, name);
			return descriptor.getReadMethod() != null;
		} catch(IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		}
		return hasProperty;
	}

	/**
	 * 判断一个对象是否有指定字段
	 *
	 * @param object
	 * @param fieldName
	 * @return
	 */
	public static boolean hasField(final Object object, final String fieldName) {
		return hasField(object.getClass(), fieldName);
	}

	/**
	 * 判断一个类是否有指定字段
	 *
	 * @param clazz
	 * @param fieldName
	 * @return
	 */
	public static boolean hasField(final Class<?> clazz, final String fieldName) {
		return getField(clazz, fieldName) != null;
	}

	@SuppressWarnings("rawtypes")
	public static boolean hasMethod(final Object object, final String methodName, final Class... parameterTypes) {
		try {
			object.getClass().getMethod(methodName, parameterTypes);
			return true;
		} catch(NoSuchMethodException | SecurityException e) {
			return false;
		}
	}

	/**
	 * 循环向上转型,获取对象的Field.
	 */
	public static Field getField(final Object object, final String fieldName) {
		return getField(object.getClass(), fieldName);
	}

	/**
	 * 循环向上转型,获取类的Field.
	 */
	public static Field getField(final Class<?> clazz, final String fieldName) {
		Field field = _getCachedField(clazz, fieldName);
		if(field != null) {
			return field;
		}
		for(Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
			try {
				field = superClass.getDeclaredField(fieldName);
				return _addToFieldCache(clazz, field);
			} catch(NoSuchFieldException e) {
				// Field不在当前类定义,继续向上转型
			}
		}
		return null;
	}

	/**
	 * 强制转换fileld可访问.
	 */
	public static void makeAccessible(final Field field) {
		if(!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
			field.setAccessible(true);
		}
	}

	public static <T> Class<T> getGenricParameterType(final Object obj) {
		if(obj == null) {
			return null;
		}
		return (Class<T>) ((ParameterizedType) obj.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public static <T> Class<T> getGenricParameterType(final Class<?> clazz) {
		return (Class<T>) ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	/**
	 * 通过反射,获得定义Class时声明的父类的第一个泛型参数的类型，支持多级继承
	 *
	 * @param targetClass
	 * @param genericSuperClass
	 * @return
	 */
	public static <T extends Type> T getGenricParameterType(final Class<?> targetClass, final Class<?> genericSuperClass) {
		return getGenricParameterType(targetClass, genericSuperClass, 0);
	}

	/**
	 * 通过反射,获得定义Class时声明的父类的第{index}个(从0开始)泛型参数的类型，支持多级继承
	 *
	 * @param targetClass
	 * @param genericSuperClass
	 * @param index
	 * @return
	 */
	public static <T extends Type> T getGenricParameterType(final Class<?> targetClass, final Class<?> genericSuperClass,
			final int index) {
		if(!genericSuperClass.isAssignableFrom(targetClass)) {
			throw new ReflectException("获取泛型参数错误，原因：[" + targetClass.getName() + "]不是[" + genericSuperClass.getName() + "]的子类");
		}
		ParameterizedType parameterizedType = getParameterizedType(targetClass, genericSuperClass);
		return (T) (parameterizedType == null ? null
				: ReflectionUtils.getParamType(parameterizedType.getActualTypeArguments()[index]));
	}

	/**
	 * 由指定类向上（按父类的继承方向）查找参数化泛型类型，返回找到的第一个参数化泛型类型
	 *
	 * @param targetClass
	 * @param genericSuperClass
	 * @return
	 */
	private static ParameterizedType getParameterizedType(final Class<?> targetClass, final Class<?> genericSuperClass) {
		Class<?> theTargetClass = targetClass;
		Type classType = theTargetClass.getGenericSuperclass();
		while(!(classType instanceof ParameterizedType)) {
			theTargetClass = theTargetClass.getSuperclass();
			classType = theTargetClass.getGenericSuperclass();
			if(theTargetClass.getSuperclass().equals(genericSuperClass)) {
				break;
			}
		}
		return (classType instanceof ParameterizedType) ? (ParameterizedType) classType : null;
	}

	public static Field[] getFields(final Class<?> clazz) {
		Set<Field> fields = new HashSet<>();
		_fillFields(clazz, fields);
		return _addToFieldsCache(clazz, fields.toArray(new Field[0]));
	}

	/**
	 * 获取指定Class的property名称列表（包含父类）
	 *
	 * @param targetClass
	 * @return
	 */
	public static String[] getFieldNames(final Class<?> clazz) {
		long start = System.nanoTime();
		List<String> propertyNames = new ArrayList<>();
		Set<Field> fields = new HashSet<>();
		_fillFields(clazz, fields);
		for(Field field : fields) {
			propertyNames.add(field.getName());
		}
		long end = System.nanoTime();
		log.debug("Get class[{}] property names list, spend time: {} ns", clazz.getName(), (end - start));
		return propertyNames.toArray(new String[0]);
	}

	private static void _fillFields(Class<?> clazz, Set<Field> allFields) {
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields) {
			if(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())
					|| Modifier.isTransient(field.getModifiers()) || field.isAnnotationPresent(MergeOmit.class)) {
				continue;
			}
			allFields.add(field);
		}
		if(!Object.class.equals(clazz)) {
			_fillFields(clazz.getSuperclass(), allFields);
		}
	}

	/**
	 * 提取集合中的对象的属性,组合成List.
	 *
	 * @param collection
	 *            来源集合.
	 * @param propertityName
	 *            要提取的属性名.
	 */
	public static <T> List<T> fetchElementPropertyToList(final Collection<?> collection, final String propertyName) {
		List<T> list = new ArrayList<>();

		try {
			for(Object obj : collection) {
				list.add((T) PropertyUtils.getProperty(obj, propertyName));
			}
		} catch(IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			log.error("", e);
		}

		return list;
	}

	/**
	 * 提取集合中的对象的属性,组合成由分割符分隔的字符串.
	 *
	 * @param collection
	 *            来源集合.
	 * @param propertyName
	 *            要提取的属性名.
	 * @param separator
	 *            分隔符.
	 */
	public static String fetchElementPropertyToString(final Collection<?> collection, final String propertyName,
			final String separator) {
		List<?> list = fetchElementPropertyToList(collection, propertyName);
		return StringUtils.join(list, separator);
	}

	public static <T> T invokeStaticMethod(Class<?> clazz, String methodName) {
		return invokeStaticMethod(clazz, methodName, null, null);
	}

	public static <T> T invokeStaticMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object[] params) {
		T r = null;
		try {
			Method m = clazz.getMethod(methodName, parameterTypes);
			r = (T) m.invoke(clazz, params);
		} catch(Exception e) {
			log.error(clazz + " has no the method: " + methodName);
		}
		return r;
	}

	public static <T> T getStaticField(Class<?> clazz, String fieldName) {
		T r = null;
		try {
			r = (T) clazz.getField(fieldName).get(clazz);
		} catch(NoSuchFieldException | IllegalAccessException e) {
			log.warn(clazz + " has no the field: " + fieldName);
		}
		return r;
	}

	/**
	 * <ul>
	 * 根据类声明创建实例，规则：
	 * </ul>
	 * <li>可实例化的类 - 直接返回实例化对象</li>
	 * <li>抽象类，接口和其他不可实例化的类 - 返回默认的子类实例，目前支持List，Set</li>
	 *
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static <T> T createInstance(Class<?> clazz) {
		try {
			return (T) clazz.newInstance();
		} catch(InstantiationException | IllegalAccessException e) {
			if(ClassUtils.isAssignable(clazz, List.class)) {
				return (T) new ArrayList();
			} else if(ClassUtils.isAssignable(clazz, Set.class)) {
				return (T) new HashSet();
			} else if(ClassUtils.isAssignable(clazz, Map.class)) {
				return (T) new HashMap();
			} else if(clazz.getName().startsWith("java.lang")) {
				return null;
			} else if(clazz.isEnum()) {
				return null;
			}
			throw new UnsupportedOperationException("can not newInstance for class: " + clazz.getName());
		}
	}

	/**
	 * 将反射时的checked exception转换为unchecked exception.
	 */
	public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
		if(e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) {
			return new IllegalArgumentException("Reflection Exception.", e);
		} else if(e instanceof InvocationTargetException) {
			return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
		} else if(e instanceof RuntimeException) {
			return (RuntimeException) e;
		}
		return new RuntimeException("Unexpected Checked Exception.", e);
	}

	@SuppressWarnings("rawtypes")
	public static <T extends Type> T getParamType(Type paramType) {
		if(paramType instanceof TypeVariable) {
			return (T) ((TypeVariable) paramType).getBounds()[0];
		}
		return (T) paramType;
	}
}
